<template>
  <div class="search">
    <div class="search-header">
      <van-icon name="arrow-left" @click="goback" />
      <van-search
        show-action
        v-model="value"
        placeholder="你在找什么？"
        shape="round"
      >
        <template #action>
          <div @click="onSearch(value)">搜索</div>
        </template>
      </van-search>
    </div>
    <van-divider />
    <div class="searchres" v-for="item in newlist" :key="item._id">
      <router-link :to="{ name: 'Detail', params: { id: item._id } }">
        <van-card
          :price="(item.price / 100).toFixed(2)"
          :title="item.name"
          :thumb="item.coverImg"
          tag="HOT"
          :origin-price="(item.price / 100 + 50).toFixed(2)"
        >
          <template #tags>
            <van-tag plain type="danger">新品</van-tag>
          </template>
        </van-card>
      </router-link>
    </div>
  </div>
</template>

<script>
import { getAllProductsAPI } from "../../api/products";

export default {
  data() {
    return {
      searchlist: [],
      newlist: JSON.parse(localStorage.getItem("searchlist")) || [],
      searchres: [],
      value: "",
    };
  },

  methods: {
    // 点击搜索按钮触发事件
    async onSearch(value) {
      //   判断是否在搜索列表页
      if (this.$route.path === "/searchlist") {
        const res = await getAllProductsAPI({ name: value });
        this.searchlist = res.searchdata;
        this.newlist = this.searchlist.filter((item) =>
          item.name.includes(value)
        );
      }
    },
    // 返回
    goback() {
      this.$router.go(-1);
    },
  },
  created() {},
};
</script>

<style>
.search {
  padding: 0 20px;
}
.search .search-header {
  display: flex;
  align-items: center;
}
.search .van-search {
  flex: 1;
}
.search .van-card__title {
  line-height: 32px;
  color: #111;
  font-size: 15px;
}
.search .van-card__price {
  color: #0058a3;
}
</style>
